package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    //查询所有的数据 没有where条件所以参数为null
    @Override
    public List<User> findAll() {

        return userMapper.selectList(null);
    }

    @Override
    public User findUserById(Integer id) {

        return userMapper.selectById(id);
    }

    //MP 可以根据对象中不为null的属性拼接where条件
    @Override
    public List<User> findUserByNS(User user) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        return userMapper.selectList(queryWrapper);
    }

    //规则: 字段与属性的逻辑运算符为 '=号'时使用实体(user)对象封装
    //查询 name="貂蝉" age> 10 岁 的用户.
    @Override
    public List<User> findUserByNA(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",user.getName())
                    .gt("age",user.getAge());
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> getUserByIds(Integer[] ids) {

        List<Integer> idList = Arrays.asList(ids);
        return userMapper.selectBatchIds(idList);
    }

    //需求:     查询sex=女 age>18
    @Override
    public List<User> getUserBySA(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("sex",user.getSex())
                .gt("age",user.getAge());
        return userMapper.selectList(queryWrapper);
    }

    //根据对象中不为null的属性充当where条件
    @Override
    public List<User> getUser(User user) {
        QueryWrapper queryWrapper = new QueryWrapper(user);
        //return userMapper.selectList(new QueryWrapper<>(user));
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteById(Integer id) {

        userMapper.deleteById(id);
    }

    @Override
    public void saveUser(User user) {

        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {

        userMapper.updateById(user);
    }

    //userMapper.update(arg1,arg2)
    //arg1: set条件的数据,
    //arg2: where条件的数据
    @Override
    public void updateUserByName(User user, String whereName) {
        //updateWrapper 与 queryWrapper 功能一样,可以混用
        UpdateWrapper<User> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("name",whereName);
        userMapper.update(user,updateWrapper);
    }
}
